package com.sskj.xgja;

import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.sskj.base.data.User;
import com.sskj.base.model.UserViewModel;

public abstract class MVPFragment<P extends BasePresenter> extends BaseFragment implements BaseView {

    protected P mPresenter;
    private boolean isFirstToUser = true;
    public static UserViewModel userViewModel;
    protected String TAG;
    public static boolean isLogin;
    public static String account;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TAG = this.getClass().getName();
        mPresenter = getPresenter();
        mPresenter.attachView(this);
        getLifecycle().addObserver(mPresenter);
        LiveDataBus.get().with(1, User.class)
                .observe(MyApplication.instance,user -> {
                    if (user != null) {
                        account = user.getAccount();
                    } else {
                        account = "";
                    }
                });
//        if (userViewModel==null) {
//            userViewModel = ViewModelProviders.of(getActivity()).get(UserViewModel.class);
//        }
//        userViewModel.getUser(getActivity()).observe(getActivity(), user -> {
//            if (user != null) {
//                isLogin = true;
//                account = user.getAccount();
//            } else {
//                isLogin = false;
//                account = "";
//            }
//        });
    }


    public boolean isLogin() {
        MVPActivity activity = (MVPActivity) getActivity();
        if (activity != null) {
            return activity.isLogin;
        }
        return false;
    }

    public String getAccount() {
        MVPActivity activity = (MVPActivity) getActivity();
        if (activity != null) {
            return activity.account;
        }
        return "";
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
         View  view= super.onCreateView(inflater, container, savedInstanceState);
        initView();
        initData();
        initListener();
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (isFirstToUser) {
                onFirstToUser();
                isFirstToUser = false;
            }
        }
    }

    public void onFirstToUser() {

    }

    public abstract P getPresenter();

}
